package com.travel.web;

import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;
import com.travel.common.util.TravelProperty;

import com.travel.web.common.AbstractAction;

public class MainAction extends AbstractAction {
	private static final long serialVersionUID = 1543596752207940860L;
	private String code;
	private String name;
	private String email;
	private String externalUrl;
	 

	public String execute() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			return authenticate(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String view = null;

		String requestUri = request.getRequestURI().replaceFirst(request.getContextPath(), "");
		

		if (request.getParameter("code") == null) {
			String url = "https://graph.facebook.com/oauth/authorize?"
					+ "scope=publish_stream,offline_access,create_event"
					+ "&client_id=" + TravelProperty.getString("facebook.api_key") 
					+ "&redirect_uri=" +  TravelProperty.getString("facebook.connect.url") 
					+ requestUri;
			externalUrl = url;
			view = "redirect";
		} else {

			view = SUCCESS;

			getUserInfo(request, response);
		}
		return view;
	}

	public void getUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String redirecttUri = TravelProperty.getString("facebook.connect.url")  + request.getRequestURI().replaceFirst(request.getContextPath(), "");
		String code = request.getParameter("code");
		if (code == null || redirecttUri == null) {
			return ;
		}

		code = request.getParameter("code");

		String url = "https://graph.facebook.com/oauth/access_token?"
				+ "client_id=" + TravelProperty.getString("facebook.api_key") 
				+ "&client_secret=" + TravelProperty.getString("facebook.secret") 
				+ "&code=" + code + "&redirect_uri=" + redirecttUri;
		
		String accessToken = readUrl(url).split("&")[0].replaceFirst("access_token=", "");
		
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		User user = facebookClient.fetchObject("me", User.class);
		
		name = user.getName();
		email = user.getEmail();
//		userService.create(user.getId(), user.getName(), user.getLink(),
//				accessToken, null);

		request.getSession().setAttribute("fb_user", user);
		request.getSession().setAttribute("fb_user_id", user.getId());
	}

	protected String readUrl(String urlString) throws IOException {
		URL url = new URL(urlString);
		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

		String response = "";
		String inputLine;

		while ((inputLine = in.readLine()) != null)
			response += inputLine;

		in.close();
		return response;
	}
	public void log(String str) {
		System.out.println(str);
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	public String getExternalUrl()
	{
	 return externalUrl;
	}
}
